package com.ucode.admin.cgms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.cgms.service.CgmsAfterSaleCompanionOrderService;
import com.ucode.cgms.service.CgmsCompanionOrderService;
import com.ucode.model.cgms.CgmsAfterSaleCompanionOrder;
import com.ucode.model.cgms.CgmsCompanionOrder;
import com.ucode.model.cgms.convert.CgmsAfterSaleCompanionOrderConvert;
import com.ucode.model.cgms.enums.CgmsAfterSaleCompanionOrderStatusEnum;
import com.ucode.model.cgms.form.CgmsAuditForm;
import com.ucode.model.cgms.vo.CgmsAfterSaleCompanionOrderVO;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.UserTypeEnum;
import com.ucode.tool.util.IdentifyUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 陪玩售后订单管理
 * @author liliang
 * @date 2023-08-15
 */
@Tag(name = "管理后台 - 陪玩社区系统 - 售后订单管理")
@RestController
@RequestMapping("/cgms/after-sale-companion-order")
@Validated
public class CgmsAfterSaleCompanionOrderController {

    @Resource
    private CgmsAfterSaleCompanionOrderService cgmsAfterSaleCompanionOrderService;
    
    @Resource
    private CgmsCompanionOrderService cgmsCompanionOrderService;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('cgms:after-sale-companion-order:query')")
    public ResponseResult<Paginator<CgmsAfterSaleCompanionOrderVO>> pageList(
            @Schema(description = "售后ID") @RequestParam(value = "id", required = false) Long id,
            @Schema(description = "订单ID") @RequestParam(value = "orderId", required = false) Long orderId,
            @Schema(description = "用户ID") @RequestParam(value = "userId", required = false) Long userId,
            @Schema(description = "售后标题") @RequestParam(value = "title", required = false) String title,
            @Schema(description = "审核状态，参见CgmsAfterSaleCompanionOrderStatusEnum枚举类", allowableValues = {"1","2","3","4","5"}) 
            @RequestParam(value = "statuz", required = false) Integer statuz,
            @Schema(description = "创建时间区间", example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]") 
            @RequestParam(value = "createTimeInterval", required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数", example = "10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        Map<String, Object> condition = new HashMap<>();
        condition.put("id", id);
        condition.put("orderId", orderId);
        condition.put("userId", userId);
        
        if(StrUtil.isNotBlank(title))
            condition.put("title", StrUtil.concat(true, title, "%"));
            
        condition.put("statuz", statuz);
        
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2) {
            condition.put("startTime", createTimeInterval[0]);
            condition.put("endTime", createTimeInterval[1]);
        }
        
        // 只查询未删除的数据
        condition.put("deltag", false);
        
        // 分页查询
        Paginator<CgmsAfterSaleCompanionOrder> paginator = cgmsAfterSaleCompanionOrderService.queryPageForList(condition, pageSize, pageNum);
        Paginator<CgmsAfterSaleCompanionOrderVO> paginatorVO = CgmsAfterSaleCompanionOrderConvert.INSTANCE.convertPage(paginator);
        
        // 补充支付相关信息
        if(CollUtil.isNotEmpty(paginatorVO.getList())) {
            Set<Long> orderIds = new HashSet<>();
            for(CgmsAfterSaleCompanionOrderVO vo : paginatorVO.getList()) {
                if(ObjUtil.isNotNull(vo.getOrderId()) && !ObjUtil.equals(vo.getOrderId(), 0L))
                    orderIds.add(vo.getOrderId());
            }
            
            // 改为查询订单列表，然后自行构建Map
            Map<Long, CgmsCompanionOrder> orderMap = cgmsCompanionOrderService.getMap(orderIds);;
            for(CgmsAfterSaleCompanionOrderVO vo : paginatorVO.getList()) {
                CgmsCompanionOrder order = orderMap.get(vo.getOrderId());
                if(ObjUtil.isNotNull(order)) {
                    vo.setPayPrice(order.getPayPrice());
                    vo.setPayTime(order.getPayTime());
                    vo.setPayType(order.getPayType());
                }
            }
        }
        return ResponseResult.success(paginatorVO);
    }

    @GetMapping("/getById/{id}")
    @Parameter(description = "主键ID", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('cgms:after-sale-companion-order:query')")
    public ResponseResult<CgmsAfterSaleCompanionOrderVO> getById(@PathVariable(name = "id", required = true) Long id) {
        CgmsAfterSaleCompanionOrder bean = cgmsAfterSaleCompanionOrderService.validate(id);
        CgmsAfterSaleCompanionOrderVO vo = CgmsAfterSaleCompanionOrderConvert.INSTANCE.convert(bean);
        
        // 补充订单支付信息
        if(ObjUtil.isNotNull(bean.getOrderId())) {
            CgmsCompanionOrder order = cgmsCompanionOrderService.selectByPrimaryKey(bean.getOrderId());
            if(ObjUtil.isNotNull(order)) {
                vo.setPayPrice(order.getPayPrice());
                vo.setPayTime(order.getPayTime());
                vo.setPayType(order.getPayType());
            }
        }
        
        return ResponseResult.success(vo);
    }

    @PostMapping("/update/{id}")
    @Parameter(description = "主键ID", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @Operation(summary = "修改售后订单")
    @PreAuthorize("@usfs.hasPermission('cgms:after-sale-companion-order:update')")
    public ResponseResult<Object> update(@PathVariable(name = "id", required = true) Long id, 
                                        @Valid @RequestBody CgmsAfterSaleCompanionOrder afterSaleOrder) {
        // 校验售后订单是否存在
        cgmsAfterSaleCompanionOrderService.validate(id);
        
        // 设置ID，确保更新正确的记录
        afterSaleOrder.setId(id);
        
        // 更新售后订单，使用update方法替代updateSelective
        int i = cgmsAfterSaleCompanionOrderService.update(afterSaleOrder);
        
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/handle")
    @Operation(summary = "处理售后申请")
    @PreAuthorize("@usfs.hasPermission('cgms:after-sale-companion-order:handle')")
    public ResponseResult<Object> handle(@Valid @RequestBody CgmsAuditForm form) {
        // 处理多条数据
        List<Long> ids = form.getIds();
        int successCount = 0;
        for (Long id : ids) {
            try {
                // 校验售后订单是否存在
                cgmsAfterSaleCompanionOrderService.validate(id);
                
                // 处理售后申请
                cgmsAfterSaleCompanionOrderService.audit(
                    id, 
                    form.getStatuz(), 
                    0L, // 系统处理，不记录具体处理人
                    UserTypeEnum.ADMIN.getCode(), 
                    form.getRemark()
                );
                
                successCount++;
            } catch (Exception e) {
                // 继续处理其他ID
            }
        }
        
        return ResponseResult.success();
    }

    @PostMapping("/logic-delete/{id}")
    @Operation(summary = "转移到回收站")
    @Parameter(description = "主键ID", name = "id", required = true, in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('cgms:after-sale-companion-order:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name = "id", required = true) Long id) {
        // 校验售后订单是否存在
        cgmsAfterSaleCompanionOrderService.validate(id);
        
        // 逻辑删除售后订单
        int i = cgmsAfterSaleCompanionOrderService.logicDeletePrimaryKey(id);
        
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量转移到回收站")
    @PreAuthorize("@usfs.hasPermission('cgms:after-sale-companion-order:logic-delete')")
    public ResponseResult<Boolean> batchLogicDeletePrimaryKey(
            @Schema(description = "编号集合", requiredMode = Schema.RequiredMode.REQUIRED)
            @NotEmpty(message = "编号集合为空") @Size(min = 1, max = 20, message = "编号集合数量为1-20条")
            @RequestParam(value = "ids", required = true) List<Long> ids) {
        
        // 使用logicDeleteByPrimaryKeys方法替代logicDeleteByIds
        int i = cgmsAfterSaleCompanionOrderService.logicDeleteByPrimaryKeys(ids);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
} 